package team.nmsg.ge.system.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import team.nmsg.ge.system.bean.SysBusinessLog;
import team.nmsg.ge.system.dao.ISystemLogDao;


@Component
public class SystemLogDaoImpl extends NMSDaoSupport implements ISystemLogDao{

	@Override
	public long querylogCount(SysBusinessLog businessLog,long startTime,long endTime) {
		
		Session hSession = getHSession();
		
		Criteria criteria = hSession.createCriteria(SysBusinessLog.class);
		
		String uName = businessLog.getOperUserName();
		String logType = businessLog.getOperKey();
		if( uName!= null && !"".equals(uName) ){
			criteria.add(Restrictions.like("operUserName", "%"+uName+"%"));
		}
		
		if(startTime!=0&&endTime!=0){
			criteria.add(Restrictions.le("operTimeStamp", endTime));
			criteria.add(Restrictions.ge("operTimeStamp", startTime));
		}
		
		if( logType!= null && !"".equals(logType)&& !logType.equals("-1")){
			criteria.add(Restrictions.eq("operKey", logType));
		}
		
		criteria.setProjection(Projections.rowCount());
		
		List list = criteria.list();
		
		Object object = list.get(0);
		
		try {
			return Long.parseLong(object.toString());
		} catch (Exception e) {
			return 0;
		}
	}

	@Override
	public List<SysBusinessLog> QuerySysLogList(int pageSize, int startIndex,
			SysBusinessLog businessLog,long startTime,long endTime) {
		
		Session hSession = getHSession();
		Criteria criteria = hSession.createCriteria(SysBusinessLog.class);
		criteria.addOrder(Order.desc("operTimeStamp"));
		String uName = businessLog.getOperUserName();
		String logType = businessLog.getOperKey();
		if( uName!= null && !"".equals(uName) ){
			criteria.add(Restrictions.like("operUserName", "%"+uName+"%"));
		}
		
		if(startTime!=0&&endTime!=0){
			criteria.add(Restrictions.le("operTimeStamp", endTime));
			criteria.add(Restrictions.ge("operTimeStamp", startTime));
		}
		
		if( logType!= null && !"".equals(logType)&&!logType.equals("-1")){
			criteria.add(Restrictions.eq("operKey", logType));
		}
		
		criteria.setFirstResult(startIndex);
		criteria.setMaxResults(pageSize);
		List list = criteria.list();
		
		return list;
	}
	
	@Override
	public void deleteLogById(String logId) {
		Session hSession = getHSession();
		Query query = hSession.createSQLQuery("delete from sysbusinesslog where logId= ?");
		query.setParameter(0, logId);
		query.executeUpdate();
	}
}
